package com.beyondbit.hr.report.controller;

import com.beyondbit.hr.api.utils.NonRollbackException;
import com.beyondbit.hr.report.model.ReportResponse;
import com.beyondbit.hr.report.service.ReportService;
import com.beyondbit.hr.report.support.ReportConverter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/")
public class ReportController {

    @Autowired
    ReportService reportService;

    @RequestMapping(value = "/report/{reportName}"
            ,produces = {ReportConverter.PDF_VALUE,ReportConverter.XLS_VALUE,MediaType.TEXT_HTML_VALUE})
    @ResponseBody
    public ReportResponse report(@PathVariable("reportName")String reportName) throws NonRollbackException {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();

        HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();

        JasperReport jr = reportService.jasperReport(reportName);
        JasperPrint jasperPrint = reportService.jasperPrint(jr,httpServletRequest);

        ReportResponse rr = new ReportResponse(jasperPrint);

        return rr;
    }
}
